<template>
  <a-card :bordered="false">
    <a-row :gutter="8">

      <a-col :span="4">
        <a-tree
          class="template-5-tree"
          :tree-data="treeData"
          :replace-fields="replaceFields"
          show-icon
          :defaultExpandedKeys="[channelCode]"
          @select="handleTreeSelect"
        >
          <!-- 自定义子节点图标 -->
          <a-icon slot="myIcon" type="unordered-list" style="color:#0c8fcf;"/>
        </a-tree>

      </a-col>

      <a-col :span="20">

        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="12" v-for="item in queryColumns" v-if="item.isQuery" :key="item.id">
                <a-form-item :label="item.columnComment"  v-if="item.htmlType==='switch'">
                  <a-select v-model="queryParam[item.javaField]" placeholder="全部">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="1">开启</a-select-option>
                    <a-select-option value="0">关闭</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item :label="item.columnComment" v-if="item.htmlType==='input'">
                  <a-input :placeholder="'输入'+item.columnComment+'模糊查询'" v-model="queryParam[item.javaField]"></a-input>
                </a-form-item>
                <a-form-item :label="item.columnComment" v-if="item.htmlType==='cat_tree'">
                  <j-category-select v-model="queryParam[item.javaField]" pcode="F01" value="F11"/>
                </a-form-item>

              </a-col>

              <a-col :md="6" :sm="12">
             <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
               <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
               <a-button type="primary" @click="handleReset" icon="reload" style="margin-left: 8px">重置</a-button>
               <a @click="handleToggleSearch" style="margin-left: 8px">
                 {{ toggleSearchStatus ? '收起' : '展开' }}
                 <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
               </a>
             </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator" style="border-top: 5px">
          <a-button @click="handleAdd" type="primary" icon="plus">添加</a-button>
        </div>
        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i>已选择&nbsp;<a style="font-weight: 600">{{
            selectedRowKeys.length }}</a>项&nbsp;&nbsp;
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
          </div>
          <a-table
            ref="table"
            bordered
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
            <template slot="sortNo" slot-scope="text, record, index">
              <a-input
                style="margin: -5px 0"
                :value="text"
                v-model="record.sortNo"
                @blur="(e) => handleSortNo(record.sortNo,record.id)"
              />
            </template>
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">
              更多 <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
               <a-menu-item>
                  <a @click="handleComment(record.id)">评论</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

            <span slot="isHot_switch" slot-scope="text, record">
              <a-switch checked-children="否" un-checked-children="是" v-model="record.isHot"  @change="(checked)=>handleField('isHot',checked,record.id)"></a-switch>
            </span>
            <span slot="status_switch" slot-scope="text, record">
              <a-switch checked-children="否" un-checked-children="是" v-model="record.status"  @change="(checked)=>handleField('status',checked,record.id)"></a-switch>
            </span>

          </a-table>
        </div>
        <!-- table区域-end -->
        <content-modal ref="modalForm" @ok="modalFormOk">
        </content-modal>
      </a-col>
    </a-row>

    <a-drawer
      title="评论"
      :maskClosable="true"
      :width="drawerWidth"
      placement="right"
      :closable="true"
      @close="handleCancel"
      :visible="commentVisible"
      style="height: 100%;overflow: auto;padding-bottom: 53px;">

      <a-form-model-item label="用户评论"
                         :labelCol="labelCol" :wrapperCol="wrapperCol" >
        <a-list size="large" style="height: 400px;overflow: auto">
          <div
            v-if="showLoadingMore"
            slot="loadMore"
            :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }"
          >
            <a-spin v-if="loadingMore" />
            <a-button v-else @click="onLoadMore()">
              更多评论
            </a-button>
          </div>
          <template v-for="(item, index) in commentList">
            <a-list-item :key="index">

              <div class="list-content" style="display: flex">
                <a-avatar slot="avatar" size="small" :src="item.member.avatarUrl"/>
                <div class="list-content-item" style="margin-left: 16px">
                  <span>{{item.member.nickName}}</span>
                  <p class="content">{{ item.content }}</p>
                  <p>{{ item.createTime }}</p>
                  <div style="font-weight: bold" v-if="item.commentNum>0" @click="getChildCommentList(item.id,index)">展开{{item.commentNum}}条回复</div>
                </div>
              </div>
              <div slot="actions">
                <a @click="showChildComment(item.id)">回复</a>
              </div>
              <div slot="actions">
                <a v-if="item.status" @click="handleStatus(false,item.id)">屏蔽</a>
                <a v-else @click="handleStatus(true,item.id)">取消屏蔽</a>
              </div>
            </a-list-item>
            <a-list-item :key="subItem.id" style="margin-left: 20px;" v-for="subItem in item.commentList">
              <div class="list-content" style="display: flex">
                <a-avatar slot="avatar" size="small" :src="subItem.member.avatarUrl"/>
                <div class="list-content-item" style="margin-left: 16px">
                  <span>{{subItem.member.nickName}}<span v-if="subItem.parentCommentMemberName"> <a-icon type="caret-right" />{{subItem.parentCommentMemberName}}</span> </span>
                  <p class="content">{{ subItem.content }}</p>
                  <p>{{ subItem.createTime }}</p>
                </div>
              </div>
              <div slot="actions">
                <a @click="showChildComment(item.id)">回复</a>
              </div>
              <div slot="actions">
                <a v-if="item.status" @click="handleStatus(false,item.id)">屏蔽</a>
                <a v-else @click="handleStatus(true,item.id)">取消屏蔽</a>
              </div>
            </a-list-item>
          </template>


        </a-list>
      </a-form-model-item>
      <a-form-model-item label="发起评论"
                         :labelCol="labelCol" :wrapperCol="wrapperCol" >
        <a-textarea v-model="comment"/>
        <a-button type="primary" @click="handleCommentSubmit">
          提交评论
        </a-button>
      </a-form-model-item>
      <j-modal
        title="评论"
        :visible="childCommentVisible"
        @close="childCommentClose"
        @cancel="childCommentClose"
        @ok="handleChildSubmit"
      >
        <a-textarea v-model="childComment"></a-textarea>
      </j-modal>
    </a-drawer>


  </a-card>
</template>

<script>
  import { getAction, postAction } from '@api/manage'
  import {queryColumnList} from '@/api/api'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import ContentModal from './ContentModal'

  export default {
    name: 'ContentList',
    mixins: [JeecgListMixin],
    components: {
      ContentModal
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        sourceId:"",
        childCommentVisible:false,
        commentList:[],
        comment:"",
        childComment:"",
        loadingMore: false,
        showLoadingMore: false,
        drawerWidth: 700,
        commentVisible:false,
        channelCode:"",
        showTable: false,
        treeData: [],
        replaceFields: {
          title: 'name',
          key: 'code'
        },
        queryParam: {},
        columns: [],
        queryColumns: [],
        url: {
          list: '/cms/content/list',
          delete: '/cms/content/delete',
          field: '/cms/content/field',
          sortNo: '/cms/content/sortNo',
          treeData: '/cms/channel/treeList',
          column: '/gen/tableColumn/list',

        },
        commentPageNo:1,
        commentPageSize:5
      }

    },
    created() {
      this.loadTreeData()
    },
    methods: {
      getCommentList() {
        postAction('/api/ums/comment/list', { sourceId: this.sourceId,pageNo:this.commentPageNo,pageSize:this.commentPageSize }).then((res) => {
          this.loadingMore = false;
          this.showLoadingMore=false
          if (res.success) {
            if (res.result.records && res.result.records.length > 0) {
              this.commentList=this.commentList.concat(res.result.records)
              if(res.result.total/this.commentPageSize>this.commentPageNo){
                this.showLoadingMore=true
              }
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      handleCommentSubmit(){
        if(!this.comment){
          this.$message.warning("请填写评论")
          return;
        }
        postAction('/api/ums/comment/add', {sourceId:this.sourceId,content:this.comment,type:"CmsContent"}).then((res) => {
          if (res.success) {
            this.commentList=[];
            this.comment=""
            this.getCommentList();
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      onLoadMore(){
        this.loadingMore = true;
        this.commentPageNo++;
        this.getCommentList();
      },
      getChildCommentList(id,index){
        postAction('/api/ums/comment/list', { sourceId: id}).then((res) => {
          if (res.success) {
            if (res.result.records && res.result.records.length > 0) {
              this.commentList[index].commentList=res.result.records
              this.$forceUpdate();
            }
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      showChildComment(id){
        this.childCommentVisible=true
        this.childCommentId=id
      },
      handleChildSubmit(){
        postAction('/api/ums/comment/add', {sourceId:this.childCommentId,content:this.childComment,type:"UmsComment"}).then((res) => {
          if (res.success) {
            this.childCommentVisible=false
            this.commentList=[];
            this.getCommentList();
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      childCommentClose(){
        this.childCommentVisible=false
      },
      handleCancel(){
        this.commentVisible=false
      },
      handleComment(id){
        this.sourceId=id
        this.commentVisible=true
        this.commentList=[]
        this.getCommentList();
      },
      loadData(){
        if(!!this.queryParam.channelCode_eq){
          postAction(this.url.list, this.queryParam).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records;
            }else{
              this.$message.warning(res.message)
            }
          }).finally(() => {
            this.loading = false
          })
        }

      },
      loadColumn() {
        queryColumnList({ channelCode_eq: this.channelCode,pageNo:1,pageSize:100,status:1,order:"asc",column:"sortNo"  }).then(res => {
          if (res.success) {
            this.columns = []
            let columns = res.result.records
            this.queryColumns=columns;
            for (let i = 0; i < columns.length; i++) {
              if (columns[i].isList) {
                let dataIndex=columns[i].javaField;
                if(!columns[i].isTransient){
                  dataIndex=columns[i].columnName.replace("_",".")
                }
                if(!!columns[i].dictCode){
                  dataIndex+="_dictText"
                }
                let c = {
                  title: columns[i].columnComment,
                  align: 'center',
                  dataIndex: '' + dataIndex + ''
                }
                if (columns[i].htmlType === 'input' || columns[i].htmlType === 'date') {
                  c.dataIndex= '' + dataIndex + ''
                }
                if (columns[i].htmlType === 'switch') {
                  c.dataIndex= columns[i].javaField+'_switch';
                  c.scopedSlots={customRender:columns[i].javaField+ '_switch'};
                }
                if (columns[i].javaField === 'sortNo') {
                  c.dataIndex= "sortNo"
                  c.scopedSlots={customRender: 'sortNo'};
                }
                if (columns[i].fieldLength !== 0) {
                  c.width = columns[i].fieldLength
                }
                this.columns.push(c)
              }
            }
            this.columns.push({
              title: '操作',
              dataIndex: 'action',
              scopedSlots: { customRender: 'action' },
              align: 'center',
              width: 170
            })
          }

          this.queryParam.channelCode_eq=this.channelCode
          this.dataSource=[]
          this.searchQuery()
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        })
      },
      handleSortNo: function (sortNo,id) {
        if(!this.url.sortNo){
          this.$message.error("请设置url.sortNo属性!")
          return
        }
        var that = this;
        postAction(that.url.sortNo, {sortNo:sortNo,id: id}).then((res) => {
          if (res.success) {
            //重新计算分页问题
            that.reCalculatePage(1)
            //that.$message.success(res.message);
            that.loadData();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      loadTreeData() {
        getAction(this.url.treeData, {}).then(res => {
          this.treeData = res.result
          this.channelCode = this.treeData[0].code
          this.$refs.modalForm.model.channelCode = this.channelCode
          this.loadColumn()
        }).finally(() => {
          // 这里是无论成功或失败都会执行的方法，在这里关闭loading
          this.loading = false
        })
      },
      // 树被选择触发的事件
      handleTreeSelect(selectedKeys) {
        if (selectedKeys.length > 0) {
          this.channelCode=selectedKeys[0];
          this.$refs.modalForm.model.channelCode = this.channelCode
          this.loadColumn()
        }

      },
      handleReset(){
        this.searchReset();

      }

    }

  }

</script>
<style scoped>
  @import '~@assets/less/common.less'

</style>
<style lang="less">
  /** 隐藏文件小图标 */
  .template-5-tree.ant-tree {
    li span.ant-tree-switcher.ant-tree-switcher-noop {
      display: none;
    }
  }
</style>